import json
import os
import shutil

class AppConfig:   
    
    def __init__(self, filepath= "config.json"):
        self.filepath = filepath
        self.info = {}
        self.read_source()
    def set_default(self):
        self.info = {}
        self.info['last_opened_assembly_play']= ''
        
    def record(self) :
        return self.info['last_opened_assembly_play']
    
    def newrecord(self, newrecord:str) :
        self.info['last_opened_assembly_play'] = newrecord
        self.update_source()
        
    def check_valid(self):
        res = {'last_opened_assembly_play'}.issubset(self.info.keys())
        if not res:
            return False
        res = os.path.exists(self.info['last_opened_assembly_play'])
        if not res:
            return False        
        return True
        
    def read_source(self):
        if os.path.exists(self.filepath):         
            try:
                with open(self.filepath, 'r', encoding='utf-8') as f:
                    self.info = json.load(f)
            except FileNotFoundError:
                raise ValueError("Error" f"The file {self.filepath} does not exist.")
            except json.JSONDecodeError:
                raise ValueError("Error" f"The file {self.filepath} is not a valid JSON file.")
        else:
            self.set_default()
            self.update_source()    
    def update_source(self):       
        try:
            with open(self.filepath, 'w', encoding='utf-8') as f:
                json.dump(self.info, f, ensure_ascii=False, indent=4)
        except Exception as e:
            raise ValueError(f"Failed to save file: {self.filepath}->{e}")
    

if __name__ == "__main__":
    filepath = "test.json"
    with open("xxx.json", 'w') as file:
        file.write('{}')     
    if os.path.exists(filepath) :
        os.remove(filepath)
    appconfig = AppConfig(filepath)
    res = appconfig.check_valid()
    if res :
        pass
    else:
        pass
    os.remove("xxx.json")
    